package pers.qianyu.service;

import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.exception.*;
import pers.qianyu.mapper.*;
import pers.qianyu.model.dto.*;
import pers.qianyu.model.entity.*;
import pers.qianyu.model.enums.*;
import pers.qianyu.model.vo.*;
import pers.qianyu.utils.*;

import java.util.*;
import java.util.stream.*;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public UserVO getUserById(Long id) {
        UserPO userPO = userMapper.selectById(id);
        if (Objects.isNull(userPO)) {
            throw new MyException(ErrorInfoEnum.INVALID_ID);
        }
        return UserVO.fromUserPO(userPO);
    }

    public void insertUser(UserDTO userDTO) {
        UserPO userPO = userDTO.toUserPO();
        userMapper.insert(userPO);
    }

    public PageVO<UserVO> getUsers(Integer page, Integer limit) {
        int offset = (page - 1) * limit;
        Page<UserPO> users = userMapper.selectPage(new Page<>(offset, limit), null);
        List<UserVO> vos = users.getRecords().stream()
                .map(UserVO::fromUserPO)
                .collect(Collectors.toList());
        PageVO<UserVO> pageVO = PageVO.<UserVO>builder()
                .records(vos.isEmpty() ? new ArrayList<UserVO>() : vos)
                .current(page)
                .size(limit)
                .total(users.getTotal())
                .build();
        return pageVO;
    }

    public void deleteUserById(Long id) {
        int res = userMapper.deleteById(id);
        if (res <= 0) {
            throw new MyException(ErrorInfoEnum.INVALID_ID);
        }
    }

    public void updateUserById(Long id, UserDTO userDTO) {
        UserPO po = userMapper.selectById(id);
        if (Objects.isNull(po)) {
            throw new MyException(ErrorInfoEnum.INVALID_ID);
        }
        UserPO poForUpdate = userDTO.toUserPO().setId(id);
        int rows = userMapper.updateById(poForUpdate);
        if (rows <= 0) {
            throw new MyException(ErrorInfoEnum.UNKNOWN_ERROR);
        }
    }

    public UserVO login(UserDTO userDTO) {
        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userDTO.getUsername())
                .eq("password", SecurityUtil.encryptPassword(userDTO.getPassword()));
        UserPO po = userMapper.selectOne(wrapper);
        if (Objects.isNull(po)) {
            throw new MyException(ErrorInfoEnum.USERNAME_PASSWORD_ERROR);
        }
        return UserVO.fromUserPO(po);
    }
}
